<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root">
        <div>
            <div>hello1</div>
            <div>hello2</div>
            <div>hello3</div>
            <ul>
                <li>li1</li>
                <li>li2</li>
                <li>li3</li>
            </ul>
        </div>
    </div>
    <script>
        class VNode {
            constructor(tag,data,value,nodeType){
                this.tag = tag && tag.toLowerCase()
                this.data = data
                this.value = value
                this.nodeType = nodeType
                this.children = []
            }
            appendChild(vnode){
                this.children.push(vnode)
            }

        }

        function getVNode(node){
            let nodeType = node.nodeType
            let _vnode = null
            if(nodeType === 1){
                let nodeName = node.nodeName
                let attrs = node.attributes
                let _attrsObj = {}
                for(let i = 0; i < attrs.length; i++){
                    _attrsObj[attrs[i].nodeName] = attrs[i].nodeValue
                }
                _vnode = new VNode(nodeName,_attrsObj,undefined,nodeType)
                let childNodes = node.childNodes
                for(let j = 0; j < childNodes.length; j++){
                    _vnode.appendChild(getVNode(childNodes[j]))
                }
            }else if(nodeType === 3){
                _vnode = new VNode(undefined,undefined,node.nodeValue,nodeType)
            }
            return _vnode
        }

        let root = document.querySelector('#root')
        let vroot = getVNode(root)
        console.log(vroot)

        //将虚拟dom转换成真实dom
        function parseNode(vnode){
            let type = vnode.nodeType
            let _node = null
            if(type === 3){
                return document.createTextNode(vnode.value)
            }else if(type === 1){
                _node = document.createElement(vnode.tag)                            
                let data = vnode.data
                Object.keys(data).forEach(key => {
                    let attrsName = key
                    let attrsValue = data[key]
                    _node.setAttribute(attrsName,attrsValue)
                })
                let children = vnode.children
                children.forEach(vChild => {
                    _node.appendChild(parseNode(vChild))
                })
                return _node
            }
            
        }

        let dom2 = parseNode(vroot)
        console.log('--',dom2)
    </script>
</body>
</html>